/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package webapps.servlet.backoffice;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import metier.tools.Filter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import metier.pojo.Client;
import metier.session.IClientManager;
import webapps.tools.Message;
import webapps.tools.ParameterModele;
import webapps.tools.Routeur;
import webapps.tools.Tools;

/**
 *
 * @author Adrien
 */
public class AdminController extends AbstractBOServlet {

    
    @EJB
    IClientManager manager;
    
    private static final String[] colonnes = { "prenom", "nom", "ville"}; 
    
    public static final String[] message  ={
        "La suppression a fonctionnée"
    };
    
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */

            List<Client> clients = null;
            HttpSession session = request.getSession(true);
            String message = "";
            int    etat    = Tools.PAS_MESSAGE;
            
            List<Filter> filtres = (List<Filter>)session.getAttribute("filtres");
            if (filtres == null)
            {
                filtres = new ArrayList<Filter>();
            }
           
           if (request.getParameter("action") != null)
           {
               
               String requete_action = request.getParameter("action");
               
               //SUPPRESSION D'UN CLIENT
               if (requete_action.equals("supprimer") && request.getParameter("id") != null && Tools.estEntier(request.getParameter("id")))
               {
                    manager.desactiverClient(Long.parseLong(request.getParameter("id")));
                    
                    if (request.getParameter("ajax") != null)
                    {
                        out.println ("OK");
                        out.flush();
                        return;
                    }
                    else
                    {
                        message = "0";
                        etat = Tools.MESSAGE_SUCCES;
                    }
               }
               //AJOUT D'UN FILTRE
               else if (requete_action.equals("search"))
               {
                   if (request.getParameter("mc") != null && !request.getParameter("mc").equals(""))
                   {
                       filtres.add(new Filter ("nom",request.getParameter("mc") ,Filter.MODE_LIKE_DEB));
                   } 
                   else if (request.getParameter("id") != null && Tools.estEntier(request.getParameter("id")))
                   {
                       long id = Long.parseLong(request.getParameter("id"));
                       Client unclient = manager.findClient(id);
                       clients = new ArrayList<Client> ();
                       if (unclient != null)
                       {
                        clients.add(unclient);
                       }
                   }
                   else if (request.getParameter("ville") != null && !request.getParameter("ville").equals(""))
                   {
                       filtres.add(new Filter("ville", request.getParameter("ville"), Filter.MODE_LIKE_DEB));
                   }
               }
               Tools.addMessage(message, etat, response);
               
               response.sendRedirect("AdminController");
               return;
           }
           else
           {
               Message m = Tools.getMessage(request, response);
               if (m != null)
               {
                message   = m.getContenu();
                etat      = m.getEtat();
               }
           }
           
           
           session.setAttribute("filtres", filtres);
           
           //APPLICATION DES FILTRES
           
           clients = manager.findClientByFilter(filtres);

           //APPLICATION DE LA PAGINATION
           int debut           = 0;
           int nombre_page     = (clients.size() / 30) +1;
           int numero_page     = 1;
           int nombre_resultat = clients.size();
           
           if (request.getParameter("p") != null && Tools.estEntier(request.getParameter("p")))
           {
               numero_page = Integer.parseInt(request.getParameter("p"));
               debut =  Tools.max(0,(numero_page) - 1) * 30;
           }
           
           if (debut <= clients.size())
           {
               clients =  clients.subList(debut, Tools.min(debut+30, clients.size()));
           }else
           {
               clients = clients.subList((nombre_page -1) * 30, clients.size());
           }
           
           
           if (etat != Tools.PAS_MESSAGE)
           {
            request.setAttribute("message",message);
            request.setAttribute("etat",etat);
           }
           
           request.setAttribute("filtres", filtres);
           request.setAttribute("clients", clients);
           request.setAttribute("numero_page", numero_page);
           request.setAttribute("nombre_page", nombre_page);
           request.setAttribute("nombre_resultat", nombre_resultat);
           
           Routeur r = new Routeur();
           ParameterModele param = new ParameterModele();
           param.setTitreNavigateur("Listes des utilisateurs");
           param.setTitrePage("Listes des utilisateurs");
           param.setPagecontenu("/backoffice/clients.jsp");
           r.router(request, response,"/backoffice/modele.jsp",param);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
